package com.doit.day04

import scala.io.{BufferedSource, Source}

object _02_电影案例 {
  def main(args: Array[String]): Unit = {
    //需求：返回每个人评论的电影名称和电影评分

    //1193_One Flew Over the Cuckoo's Nest (1975)_Drama|action
    val movies: List[String] = Source.fromFile("C:\\Users\\34650\\Desktop\\课程资料\\资料\\movies.txt").getLines().toList

    //1_1193_5_978300760
    val ratings: List[String] = Source.fromFile("C:\\Users\\34650\\Desktop\\课程资料\\资料\\ratings.txt").getLines().toList

    val movies_map: Map[String, (String, String)] = movies.map(line => {
      //1193_One Flew Over the Cuckoo's Nest (1975)_Drama|action
      val arr: Array[String] = line.split("_")
      //电影id   电影名称  电影类型
      (arr(0), (arr(1), arr(2)))
    }).toMap

    val ratings_map: List[(String, String, String, String)] = ratings.map(line => {
      val arr: Array[String] = line.split("_")
      //1_1193_5_978300760
      (arr(0), arr(1), arr(2), arr(3))
    })

    //统计每个年份电影的平均分

    //应该怎么做这个需求？？
    /*
        map的方法

        怎么讲电影的名称和电影的评分关联到一起去呢？

        评论的电影名称和电影评分

        年份在movies里面  评分在ratings里面

        我如果能拿到一个List((年份，评分))
     */

 /*   val year_score: List[(String, Double)] = ratings_map.map(tp => {
      val movie_id: String = tp._2
      val score: Double = tp._3.toDouble
      //根据电影id获取到年份
      val name_type: (String, String) = movies_map.getOrElse(movie_id, (null, null))
      //获取到电影名称
      val movie_name: String = name_type._1
      if (movie_name == null) {
        ("9999", score)
      } else {
        (movie_name.substring(movie_name.length - 5, movie_name.length - 1), score)
      }
    })

    year_score.groupBy(_._1)
      .map(tp=>{
        val year: String = tp._1
        (year,(tp._2.map(_._2).sum/tp._2.size).formatted("%.2f").toDouble)
      })
      .toList
      .sortBy(_._1)
      .foreach(println)*/


    //这种是可以得到结果的，但是效率极其低下
    /*    for (mov <- movies_map) {
          val movie_id: String = mov._1
          for (rat <- ratings_map) {
            if(movie_id.equals(rat._2)){
              //==> 1,One Flew Over the Cuckoo's Nest (1975),5
              println((movie_id,mov._2,rat._3.toInt))
            }
          }
        }*/

    //要 电影id  电影名称  电影评分  ==》用电影id去获取电影名称
        for (elem <- ratings_map) {
          val movie_id: String = elem._2
          if(movie_id.equals("1") || movie_id.equals("2")){
            val tuple: (String, String) = movies_map.getOrElse(movie_id, (null,null))
            println((movie_id,tuple._1,elem._3.toInt))
          }

        }
  }

}
